<template>
  <el-tabs
    v-model="activeName"
    class="audit-logs app-container"
    type="card"
    @tab-click="handleTabClick"
  >
    <el-tab-pane
      label="用户管理"
      name="first"
    >
      <paged-table
        ref="altable"
        :entity-name="entityName"
        :request-param="pagerequest"
        :is-complex-layout="true"
      >
        <template slot="FilterItems">
          <el-form label-position="top">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="时间">
                  <el-date-picker
                    v-model="datePickerRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    class="filter-item"
                    style="width:100%"
                    @change="handleExectionTimeChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户名">
                  <el-input v-model="pagerequest.userName" />
                </el-form-item>
              </el-col>
            </el-row>
            <div v-if="isShowSeniorFilter">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="服务">
                    <el-input v-model="pagerequest.serviceName" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="持续时间">
                    <el-input
                      v-model="pagerequest.minExecutionDuration"
                      style="width:100px"
                      @blur="handleNumberClick('min')"
                    />
                    -
                    <el-input
                      v-model="pagerequest.maxExecutionDuration"
                      style="width:100px"
                      @blur="handleNumberClick('max')"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="操作">
                    <el-input v-model="pagerequest.methodName" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="错误状态">
                    <el-select
                      v-model="pagerequest.hasException"
                      style="width:100%"
                    >
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="浏览器">
                    <el-input v-model="pagerequest.browserInfo" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form>

          <div style="margin-top:20px;">
            <el-link
              type="info"
              @click.native="isShowSeniorFilter=!isShowSeniorFilter"
            ><i
              :class="[!isShowSeniorFilter?'el-icon-arrow-down':'el-icon-arrow-up']"
              style="font-weight:bold"
            /> {{ !isShowSeniorFilter?'显示':'隐藏' }}高级过滤</el-link>
          </div>

        </template>

        <el-button
          slot="ExtendButtons"
          class="filter-item"
          type="success"
          :loading="auditlogstoExcelLoading"
          @click="exportAuditLogsToExcel"
        >
          <svg-icon icon-class="excel" />
          导出Excel
        </el-button>

        <template slot="TableColumns">
          <el-table-column
            :label="L('Actions')"
            align="center"
            width="50"
          >
            <template slot-scope="{row}">
              <el-button
                size="mini"
                icon="el-icon-search"
                circle
                @click="showAuditLogDetail(row)"
              />
            </template>
          </el-table-column>

          <el-table-column
            sortable="custom"
            prop="executionTime"
            label="时间"
            width="180"
          >
            <template slot-scope="{row}">
              <i
                v-if="!row.exception"
                class="el-icon-success"
                style="color:green"
              />
              <i
                v-else
                class="el-icon-error"
                style="color:red"
              />

              <span style="margin-left: 10px">{{ row.executionTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            sortable="custom"
            prop="userName"
            label="用户名"
          />
          <el-table-column
            prop="serviceName"
            label="服务"
            show-overflow-tooltip
          />
          <el-table-column
            prop="methodName"
            label="操作"
            show-overflow-tooltip
          />
          <el-table-column
            prop="executionDuration"
            label="持续时间"
          >
            <template slot-scope="{row}">
              <span style="margin-left: 10px">{{ row.executionDuration }} ms</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="clientIpAddress"
            label="IP地址"
          />
          <el-table-column
            prop="clientName"
            label="客户端"
            show-overflow-tooltip
          />
          <el-table-column
            show-overflow-tooltip
            prop="browserInfo"
            label="浏览器"
          />

        </template>
      </paged-table>

      <div>
        <el-dialog
          title="审计日志详情"
          :visible.sync="dialogAuditLogVisible"
          top="3vh"
          width="60%"
        >
          <div class="audit-title">用户信息</div>
          <el-row>
            <el-col :span="6">
              用户名:
            </el-col>
            <el-col :span="18">
              {{ dialogAutitLogRow.userName }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              IP地址:
            </el-col>
            <el-col :span="18">
              {{ dialogAutitLogRow.clientIpAddress }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              客户端:
            </el-col>
            <el-col :span="18">
              {{ dialogAutitLogRow.clientName }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              浏览器:
            </el-col>
            <el-col :span="18">
              {{ dialogAutitLogRow.browserInfo }}
            </el-col>
          </el-row>

          <div class="audit-title">操作信息</div>
          <el-row>
            <el-col :span="6">
              服务:
            </el-col>
            <el-col :span="18">
              {{ dialogAutitLogRow.serviceName }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              操作:
            </el-col>
            <el-col :span="18">
              {{ dialogAutitLogRow.methodName }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              时间:
            </el-col>
            <el-col :span="18">
              {{ dialogAutitLogRow.executionTime | parseTime }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              持续时间:
            </el-col>
            <el-col :span="18">
              {{ dialogAutitLogRow.executionDuration }} ms
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              参数:
            </el-col>
            <el-col :span="18">
              {{ dialogAutitLogRow.parameters }}
            </el-col>
          </el-row>

          <div class="audit-title">自定义数据</div>
          <el-row>
            <el-col :span="24">
              {{ dialogAutitLogRow.customData }}
            </el-col>
          </el-row>

          <div class="audit-title">错误状态</div>
          <el-row>
            <el-col :span="24">
              <div v-if="!dialogAutitLogRow.exception">
                <i
                  class="el-icon-success"
                  style="color:green"
                /> 成功
              </div>
              <div v-else>
                <pre>
                {{ dialogAutitLogRow.exception }}
                </pre>
              </div>
            </el-col>
          </el-row>

          <span
            slot="footer"
            class="dialog-footer"
          >
            <el-button @click="dialogAuditLogVisible = false">关闭</el-button>
          </span>
        </el-dialog>
      </div>
    </el-tab-pane>

    <el-tab-pane
      label="更改日志"
      name="second"
    >
      <paged-table
        ref="ectable"
        :entity-name="ecEntityName"
        :request-param="ecPagerequest"
        :is-complex-layout="true"
      >
        <template slot="FilterItems">
          <el-form label-position="top">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="时间">
                  <el-date-picker
                    v-model="ecDatePickerRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    class="filter-item"
                    style="width:100%"
                    @change="handleChangeTimeChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户名">
                  <el-input v-model="ecPagerequest.userName" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="对象">
                  <el-select
                    v-model="ecPagerequest.entityTypeFullName"
                    style="width:100%"
                  >
                    <el-option
                      v-for="item in ecOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>

        <el-button
          slot="ExtendButtons"
          class="filter-item"
          type="success"
          :loading="entityChangesToExcelLoading"
          @click="exportEntityChangesToExcel"
        >
          <svg-icon icon-class="excel" />
          导出Excel
        </el-button>

        <template slot="TableColumns">
          <el-table-column
            :label="L('Actions')"
            align="center"
            width="100"
          >
            <template slot-scope="{row}">
              <el-button
                size="mini"
                icon="el-icon-search"
                circle
                @click="showEntityChangeDetail(row)"
              />
            </template>
          </el-table-column>

          <el-table-column
            prop="entityTypeFullName"
            label="对象"
            show-overflow-tooltip
          >
            <template slot-scope="{row}">
              {{ row.entityTypeFullName }}

              <el-tag :type="ecTagType(row.changeType)">{{ ecChangeTypeText(row.changeType) }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            sortable="custom"
            prop="userName"
            label="用户名"
          />

          <el-table-column
            sortable="custom"
            prop="changeTime"
            label="时间"
          >
            <template slot-scope="{row}">
              <span style="margin-left: 10px">{{ row.changeTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>

        </template>

      </paged-table>

      <div>
        <el-dialog
          title="更改日志详情"
          :visible.sync="dialogEngityChangeVisible"
          top="3vh"
          width="60%"
        >
          <div class="audit-title">对象信息</div>
          <el-row>
            <el-col :span="6">
              对象:
            </el-col>
            <el-col :span="18">
              {{ dialogEngityChangeRow.entityTypeFullName }}
              <el-tag :type="ecTagType(dialogEngityChangeRow.changeType)">{{ ecChangeTypeText(dialogEngityChangeRow.changeType) }}</el-tag>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              用户名:
            </el-col>
            <el-col :span="18">
              {{ dialogEngityChangeRow.userName }}
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              时间:
            </el-col>
            <el-col :span="18">
              {{ dialogEngityChangeRow.changeTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}
            </el-col>
          </el-row>

          <div class="audit-title">属性明细</div>
          <el-table
            :data="dialogEngityChangeRow.propData"
            stripe
            style="width: 100%"
          >
            <el-table-column
              prop="propertyName"
              label="属性"
              width="180"
            />
            <el-table-column
              prop="propertyTypeFullName"
              label="属性类型"
              width="180"
            />
            <el-table-column
              prop="newValue"
              label="新值"
            />
            <el-table-column
              prop="originalValue"
              label="原始值"
            />
          </el-table>

          <span
            slot="footer"
            class="dialog-footer"
          >
            <el-button @click="dialogEngityChangeVisible = false">关闭</el-button>
          </span>
        </el-dialog>
      </div>
    </el-tab-pane>

    <download-temp-file ref="downloadTempFile" />

  </el-tabs>

</template>

<script>
import pagedTable from '@/components/PagedTable'
import downloadTempFile from '@/components/DownloadTempFile'

import { parseTime } from '@/utils'
import { mapActions, mapState } from 'vuex'

export default {
  name: 'AuditLogs',
  components: { pagedTable, downloadTempFile },
  data() {
    return {
      activeName: 'first',
      entityName: 'auditlogs',
      pagerequest: { startDate: parseTime(new Date() - 3600 * 1000 * 24),
        endDate: parseTime(new Date()),
        userName: null,
        serviceName: null,
        minExecutionDuration: null,
        maxExecutionDuration: null,
        methodName: null,
        hasException: null,
        browserInfo: null },
      datePickerRange: [new Date() - 3600 * 1000 * 24, new Date()],
      dialogAuditLogVisible: false,
      dialogAutitLogRow: {},
      options: [{
        value: null,
        label: '全部'
      }, {
        value: false,
        label: '成功'
      }, {
        value: true,
        label: '出现错误'
      }],
      isShowSeniorFilter: false,

      ecEntityName: '',
      ecPagerequest: { startDate: parseTime(new Date() - 3600 * 1000 * 24),
        endDate: parseTime(new Date()),
        userName: null,
        entityTypeFullName: null
      },
      ecDatePickerRange: [new Date() - 3600 * 1000 * 24, new Date()],
      ecOptions: [{
        value: null,
        label: '全部'
      }],
      dialogEngityChangeVisible: false,
      dialogEngityChangeRow: {}
    }
  },
  computed: {
    ...mapState('auditlogs', ['auditlogstoExcelLoading']),
    ...mapState('entityChanges', ['entityChangesToExcelLoading'])
  },
  methods: {
    ...mapActions('auditlogs', ['getAuditLogsToExcel']),
    ...mapActions('entityChanges', ['getEntityHistoryObjectTypes', 'getEntityChangesToExcel', 'getEntityPropertyChanges']),

    ecTagType(type) {
      var result = ''
      switch (type) {
        case 0:
          result = 'success'
          break
        case 1:
          result = 'info'
          break
        case 2:
          result = 'danger'
          break
      }
      return result
    },

    ecChangeTypeText(type) {
      switch (type) {
        case 0:
          return '添加'
        case 1:
          return '修改'
        case 2:
          return '删除'
      }
    },

    handleNumberClick(val) {
      console.log(val)
      if (val === 'min') {
        this.pagerequest.minExecutionDuration = this.pagerequest.minExecutionDuration.replace(/[^\d]/g, '')
      } else {
        this.pagerequest.maxExecutionDuration = this.pagerequest.maxExecutionDuration.replace(/[^\d]/g, '')
      }
    },

    async handleTabClick({ name }, event) {
      if (name === 'second' && this.ecEntityName === '') {
        this.ecEntityName = 'entityChanges'
        var objectTypes = await this.getEntityHistoryObjectTypes()
        var tmps = objectTypes.map(o => { return { label: o.name, value: o.value } })
        this.ecOptions = this.ecOptions.concat(tmps)

        this.$nextTick(async() => {
          this.$refs.ectable.initialize()
        })
      }
    },

    // EntityChanges

    async exportEntityChangesToExcel() {
      var fileDto = await this.getEntityChangesToExcel({ data: this.ecPagerequest })
      this.$refs.downloadTempFile.download(fileDto)
    },

    async showEntityChangeDetail(row) {
      this.dialogEngityChangeRow = row
      var d = await this.getEntityPropertyChanges({ data: { entityChangeId: row.id }})
      this.dialogEngityChangeRow.propData = d

      this.$nextTick(() => { this.dialogEngityChangeVisible = true })
    },

    // AuditLogs

    async exportAuditLogsToExcel() {
      var fileDto = await this.getAuditLogsToExcel({ data: this.pagerequest })
      this.$refs.downloadTempFile.download(fileDto)
    },

    handleExectionTimeChange(val) {
      if (val === null) {
        this.pagerequest.startDate = null
        this.pagerequest.endDate = null
        return
      }
      if (val.length > 0) {
        this.pagerequest.startDate = parseTime(val[0])
      }
      if (val.length > 1) {
        this.pagerequest.endDate = parseTime(val[1])
      }
    },

    handleChangeTimeChange(val) {
      if (val === null) {
        this.ecPagerequest.startDate = null
        this.ecPagerequest.endDate = null
        return
      }
      if (val.length > 0) {
        this.ecPagerequest.startDate = parseTime(val[0])
      }
      if (val.length > 1) {
        this.ecPagerequest.endDate = parseTime(val[1])
      }
    },

    showAuditLogDetail(row) {
      this.dialogAuditLogVisible = true
      this.dialogAutitLogRow = row
    }
  }
}
</script>

<style lang="scss">
.audit-logs {
  .el-form--label-top {
    .el-form-item__label {
      padding: 0px;
    }
  }
  .el-form {
    .el-form-item,
    .el-row,
    .filter-container .filter-item {
      margin-bottom: 0px;
    }
  }
}

.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
</style>

<style scoped>
.audit-title {
  font-size: 20px;
  margin-bottom: 20px;
  font-weight: bold;
}

.el-tab-pane .app-container {
  padding: 0px;
}
</style>

